<template>
  <div class="app-container">
    <div class="ibox">
      <header class="ibox-header">
        <h5><i class="el-icon-edit"></i>&nbsp;&nbsp;门卡授权</h5>
        <div class="ibox-tools">
          <span
            >使用之前请先注册控件,连接读写器,目前仅IE浏览器支持控件的加载</span
          >
        </div>
      </header>
      <article class="ibox-content">
        <el-form :model="exampleForm" label-width="110px">
          <el-input
            type="textarea"
            :rows="10"
            placeholder="请输入内容"
            v-model="consolelog"
          >
          </el-input>
          <div id="app">
            <img :src="idcardimg" />
          </div>
          <div id="opendoor">
            <img :src="opendoorimg" />
          </div>
          <!-- <el-input type="input" placeholder="服务器地址" v-model="serverip">
          </el-input>
          <el-input type="input" placeholder="用户名" v-model="username">
          </el-input>
          <el-input type="password" placeholder="密码" v-model="password">
          </el-input>
          <el-input type="input" placeholder="主题" v-model="topic">
          </el-input>
          <el-button type="primary" size="small" icon="el-icon-search" @click="sub">订阅</el-button>
          <el-button type="primary" size="small" icon="el-icon-search" @click="pub">发布</el-button>

          <el-input type="textarea" :rows="5" placeholder="收到的消息" v-model="recemsg">
          </el-input>-->

          <div class="hr-line-dashed"></div>
          <div style="float:center;">
            <el-button
              type="primary"
              size="small"
              icon="k-icon-mendoor13"
              @click="initReader"
              >开启</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="exitReader"
              >关闭</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="el-icon-search"
              @click="dcCard"
              >寻卡</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="el-icon-search"
              @click="dcAuth"
              >授权</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="k-icon-mendoor13"
              @click="dcWrite"
              >写卡</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="k-icon-mendoor13"
              @click="clearConsole"
              >清空</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="k-icon-mendoor13"
              @click="readIdcardInfo"
              >读身份证Hd900</el-button
            >
            <el-button
              type="primary"
              size="small"
              icon="k-icon-mendoor13"
              @click="readIdcardInfoHd100"
              >读身份证Hd100</el-button
            >
          </div>
        </el-form>
      </article>
    </div>
  </div>
</template>

<script>
let mqttClient, clientId
export default {
  name: 'doorCardAuth',
  data() {
    return {
      files: [],
      exampleForm: {
        rowId: undefined,
        type: '',
        title: '',
        status: ''
      },
      reader: null,
      reader100: null,
      reader900: null,
      idcardimg: null,
      consolelog: '控制台：',
      serverip: null,
      username: null,
      password: null,
      topic: null,
      recemsg: null,
      clientId: null
    }
  },
  created() {
    // 引入mqtt
    const mqtt = require('mqtt')
    const username = 'admin'
    const password = 'mp@ssw0rd!Qaz2wSX'
    const url = 'ws://47.107.123.34:8083/mqtt'
    const topics = { openDoorRecord: 0, monit: 2 }

    // keepalive: 60 seconds, set to 0 to disable
    // reschedulePings: reschedule ping messages after sending packets (default true)
    // clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8)
    // protocolId: 'MQTT'
    // protocolVersion: 4
    // clean: true, set to false to receive QoS 1 and 2 messages while offline
    // reconnectPeriod: 1000 milliseconds, interval between two reconnections
    // connectTimeout: 30 * 1000 milliseconds, time to wait before a CONNACK is received
    // username: the username required by your broker, if any
    // password: the password required by your broker, if any
    // incomingStore: a Store for the incoming packets
    // outgoingStore: a Store for the outgoing packets
    // queueQoSZero: if connection is broken, queue outgoing QoS zero messages (default true)
    // customHandleAcks: MQTT 5 feature of custom handling puback and pubrec packets. Its callback:
    // 建立连接
    mqttClient = mqtt.connect(url, {
      username,
      password
    })
    // 订阅主题
    mqttClient.subscribe(topics)

    // 连接事件
    mqttClient.on('connect', () => {
      // console.log('mqtt connected')
    })
    // 重连事件
    mqttClient.on('reconnect', () => {
      // console.log('mqtt reconnected')
    })
    // 连接断开事件
    mqttClient.on('close', () => {
      // console.log('mqtt closed')
    })
    // 连接结束事件
    mqttClient.on('end', () => {
      // console.log('mqtt end')
    })
    // 客户端离线事件
    mqttClient.on('offline', () => {
      // console.log('mqtt offline')
    })
    // 错误事件
    mqttClient.on('error', error => {
      // console.log('mqtt error:' + error)
    })
    // 发送数据包事件
    mqttClient.on('packetsend', packet => {
      // console.log('mqtt packetsend:' + packet)
    })
    // 接受数据包事件
    mqttClient.on('packetreceive', packet => {
      // console.log('mqtt packetreceive:' + packet)
    })
    // 接收订阅主题消息事件
    mqttClient.on('message', (topic, message) => {
      this.recemsg = message.toString()
      var data = message.toString()
      var obj = JSON.parse(data)
      // bussiness here
      if (topic === 'monit') {
        // anychat bussiness
        const flag = obj.flag
        const roomId = obj.roomId
        const deviceId = obj.deviceId
      } else if (topic === 'openDoorRecord') {
        // 开门记录业务
        const community = obj.community
        const building = obj.building
        const unit = obj.unit
        const room = obj.room
        const username = obj.username
        const url = obj.url
        this.opendoorimg = url
      }
    })
    this.readerd8().then(d8 => {
      this.reader = d8
    })
    this.readerHd900().then(hd900 => {
      this.reader900 = hd900
    })
    this.readerHd100().then(hd100 => {
      this.reader100 = hd100
    })
  },
  methods: {
    upload(options) {
      this.uploadForElement(options)
    },
    readIdcardInfo() {
      const data = this.reader900.ReadIDCardBaseInfo()
      alert(data)
    },
    readIdcardInfoHd100() {
      this.reader100.getInfo()
      this.consolelog += '\r\n' + this.reader100.pName
      this.consolelog += '\r\n' + this.reader100.pSex
      this.consolelog += '\r\n' + this.reader100.pBirth
      this.consolelog += '\r\n' + this.reader100.pNation
      this.consolelog += '\r\n' + this.reader100.pEffectData
      this.consolelog += '\r\n' + this.reader100.pExpire
      this.consolelog += '\r\n' + this.reader100.pCertNo
      this.consolelog += '\r\n' + this.reader100.pDepartment
      this.consolelog += '\r\n' + this.reader100.pAddress
      this.consolelog += '\r\n' + this.reader100.pBmpFileData
      const picfile = this.reader100.pBmpFileData
      this.idcardimg = 'data:image/jpg;base64,' + picfile
    },
    initReader() {
      const icdev = this.reader.dc_init(100, 115200)
      this.reader.dc_beep(10)
      if (icdev < 0) {
        this.consolelog += '\n初始化读卡器失败，请检查连接是否成功'
      }
      this.consolelog += '\n' + icdev
    },
    sub() {
      // console.log('mqtt client has already connected, clientId:' + clientId)
    },
    pub() {
      const data = {
        deviceId: '8817030277',
        flag: '0',
        roomId: 159
      }
      // client.publish('topic', 'message', {qos: 1, retain: true})
      mqttClient.publish(
        'openDoorRecord',
        JSON.stringify(data),
        { qos: 1, retain: true },
        error => {
          // console.log(error || '消息发布成功')
        }
      )
    },
    exitReader() {
      const icdev = this.reader.dc_exit()
      this.reader.dc_beep(10)
    },
    dcCard() {
      this.reader.dc_card_double(0)
      const st = this.reader.get_bstrRBuffer_asc
      alert(st)
    },
    dcWrite() {
      const cardno = '88888888888888888888'
      let ret
      // 调用控件对象dc_init方法，初始化端口
      ret = this.reader.dc_init(100, 115200)
      // 成功则返回串口标识符>0，失败返回负值，见错误代码表
      if (ret < 0) {
        alert('初始化失败！')
        return
      } else if (ret > 0) {
        // 发卡
        ret = this.reader.dc_card_double(0) // 0为单卡操作模式
        this.reader.get_bstrRBuffer_asc
        if (ret !== 0) {
          alert('未发现卡片！')
          this.reader.dc_beep(10)
          this.reader.dc_exit()
          return
        } else {
          // 密钥加载及认证
          this.reader.put_bstrSBuffer_asc = 'FDB0916AC12FFF07806977681FE2ABC9'
          this.reader.dc_load_key(0, 13)
          ret = this.reader.dc_authentication(0, 13)
          if (ret !== 0) {
            alert('认证失败')
            this.reader.put_bstrSBuffer_asc = 'FFFFFFFFFFFFFF078069FFFFFFFFFFFF' // 还原设备认证key
            this.reader.dc_load_key(0, 13)
            this.reader.dc_beep(10)
            this.reader.dc_exit()
            return
          } else {
            this.reader.put_bstrSBuffer_asc = cardno + '000000000000'
            ret = this.reader.dc_write(52)
            if (ret !== 0) {
              this.reader.dc_beep(10)
              this.reader.put_bstrSBuffer_asc =
                'FFFFFFFFFFFFFF078069FFFFFFFFFFFF' // 还原设备认证key
              this.reader.dc_load_key(0, 13)
              this.reader.dc_exit()
              alert('写入失败！')
              return
            } else {
              this.reader.put_bstrSBuffer_asc =
                'FFFFFFFFFFFFFF078069FFFFFFFFFFFF' // 还原设备认证key
              this.reader.dc_load_key(0, 13)
              this.reader.dc_beep(100)
              this.reader.dc_exit()
              alert('发卡成功！')
            }
          }
        }
      }
    },
    dcAuth() {
      let ret = null
      const key = 'FFFFFFFFFFFFFF078069FFFFFFFFFFFF'
      const authkeys = [
        'FDB0916AC12FFF078069B729FBC3265D',
        'FDB0916AC12FFF078069F89EF53AC07B',
        'FDB0916AC12FFF078069B4E87F67CD2A',
        'FDB0916AC12FFF07806977681FE2ABC9',
        'FDB0916AC12FFF07806983EA74BF55B1',
        'FDB0916AC12FFF07806932DAEE66CBD4',
        'FDB0916AC12FFF0780695BCC7AB9C63A',
        'FDB0916AC12FFF078069C8877BD45A09',
        'FDB0916AC12FFF078069B729FBC3265D',
        'FDB0916AC12FFF078069B729FBC3265D',
        'EBDEBDEBDEBDFF078069142142142142',
        'FDB0916AC12FFF078069B729FBC3265D',
        'FDB0916AC12FFF078069B729FBC3265D',
        'FDB0916AC12FFF078069B729FBC3265D',
        'FDB0916AC12FFF078069B729FBC3265D',
        'FDB0916AC12FFF078069B729FBC3265D'
      ]
      for (let i = 0; i < 15; i++) {
        this.reader.put_bstrSBuffer_asc = key
        ret = this.reader.dc_authentication(0, i)
        if (ret !== 0) {
          // console.log('鉴权失败')
        } else {
          // console.log('鉴权成功')
        }
      }
      for (let i = 0; i < 15; i++) {
        this.reader.put_bstrSBuffer_asc = key
        ret = this.reader.dc_authentication(0, i)
        this.reader.put_bstrSBuffer_asc = authkeys[i]
        ret = this.reader.dc_write(i * 4 + 3)
        if (ret !== 0) {
          // console.log('写入失败')
        } else {
          // console.log('写入成功')
        }
      }
      this.reader.dc_beep(100)
    },
    clearConsole() {
      this.consolelog = ''
    }
  },
  destoryed() {
    mqttClient.disconnect()
  },
  components: {}
}
</script>

<style scoped></style>
